<template>
  <div class="app-container category">
    <div class="card-box">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleToCreate">添加分类</el-button>
      </div>
    </div>
    <div class="card-box">
      <el-table v-loading="categoryStore.loading.list" :data="categoryStore.list">
        <el-table-column label="ID" prop="id" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="是否置顶">
          <template #default="scope">{{ scope.row.is_index ? "是" : "否" }}</template>
        </el-table-column>
        <el-table-column label="上级分类">
          <template #default="scope">
            {{ scope.row.parent ? scope.row.parent.name : "无" }}
          </template>
        </el-table-column>
        <el-table-column label="所属类目">
          <template #default="scope">
            <el-link type="primary">
              {{ scope.row.subject ? scope.row.subject.name : "无" }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="类目图标">
          <template #default="{ row }">
            <el-image
              :src="row.subject ? row.subject.image_url : ''"
              lazy
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleToEditor(scope.row)">
              编辑
            </el-button>
            <el-popconfirm
              title="是否继续删除该分类？"
              type="error"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="query.page"
        v-model:page-size="query.size"
        style="margin-top: 10px"
        background
        :total="categoryStore.totalCount"
        @change="categoryStore.fetchCategoryList(query)"
      />
    </div>
    <el-dialog v-model="formVisible" :close-on-click-modal="false" :title="dialogTitle">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属类目" prop="subject">
          <el-select v-model="form.subject" placeholder="请选择所属类目" clearable>
            <el-option
              v-for="item in subjectStore.list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.subject" label="上级分类" prop="parent">
          <el-select v-model="form.parent" clearable placeholder="请选择上级分类">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="图标" prop="image_url">
          <image-upload v-model="form.image_url" :limit="1" />
        </el-form-item>
        <el-form-item label="排序" prop="sequence">
          <el-input v-model="form.sequence" type="number" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="是否置顶" prop="is_index">
          <el-switch v-model="form.is_index" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="categoryStore.loading.create || categoryStore.loading.update"
            @click="handleConfirm"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import useCategoryStoreHook from "@/store/modules/goods/category";
import { CategoryItem, CategoryListParams, CategoryFormData } from "@/api/goods/category";
import { cloneDeep } from "lodash-es";
import { useSubjectStore } from "@/store/modules/merchant/subject";

const subjectStore = useSubjectStore();

const categoryStore = useCategoryStoreHook();

const options = ref<CategoryItem[]>([]);

const defaultQuery: CategoryListParams = {
  page: 1,
  size: 10,
};

const query = reactive<CategoryListParams>(cloneDeep(defaultQuery));

const formRef = ref();

const formVisible = ref<boolean>(false);

const formType = ref<"create" | "editor">("create");

const defaultForm: Partial<CategoryFormData> = {
  parent: undefined,
  is_index: true,
  name: "",
  image_url: "",
  subject: undefined,
  is_active: true,
};

const form = reactive<Partial<CategoryFormData>>(cloneDeep(defaultForm));

const rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
};

const dialogTitle = computed(() => {
  return formType.value === "create" ? "添加分类" : "编辑分类";
});

watch(formVisible, (val) => {
  if (!val) {
    formRef.value.resetFields();
    Object.assign(form, cloneDeep(defaultForm));
  }
});

watch(
  () => form.subject,
  async (val) => {
    form.parent = undefined;
    if (val) {
      const response = await categoryStore.fetchSubjectCategoryList({ subject: String(val) });
      if (response) {
        options.value = response;
      }
    }
  }
);

function handleToCreate() {
  formType.value = "create";
  formVisible.value = true;
}

function handleToEditor(item: CategoryItem) {
  Object.assign(form, item);
  form.subject = item.subject?.id;
  form.image_url = item.image_url ? item.image_url : "";
  formType.value = "editor";
  formVisible.value = true;
}

async function handleDelete(id: number) {
  await categoryStore.fetchDeleteCategory(id);
  await categoryStore.fetchCategoryList(query);
}

function handleResetQueryForm() {
  Object.assign(query, defaultQuery);
  categoryStore.fetchCategoryList(query);
}

async function handleConfirm() {
  const valid = await formRef.value.validate();
  if (!valid) {
    return;
  }
  if (valid) {
    if (formType.value == "create") {
      const res = await categoryStore.fetchCreateCategory(form);
      if (res) {
        formVisible.value = false;
        await categoryStore.fetchCategoryList(query);
      }
    } else if (formType.value == "editor") {
      const res = await categoryStore.fetchUpdateCategory(form);
      if (res) {
        formVisible.value = false;
        await categoryStore.fetchCategoryList(query);
      }
    }
  }
}

onMounted(async () => {
  await subjectStore.fetchSubjectList({ page: 1, size: 99999 });
  await categoryStore.fetchCategoryList(query);
});
</script>

<style lang="scss" scoped></style>
